package business.service.user;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import business.entity.Card;
import business.entity.SyncData;

import util.data.carddao.ICardDataContext;
import util.web.WebServiceHelper;

import app.MyApplication;

public class CardSyncService {
	private final static String urlname = MyApplication.url + "/update";
	
	/**
	 * 完成同步
	 * @param username 用户名
	 * @param pwd 密码
	 * @return 是否同步成功
	 * @throws IOException 网络传输出现问题
	 * @throws SQLException
	 */
	public boolean update(String username, String pwd) throws IOException, SQLException{
		SyncData data = new SyncData();
		data.setUsername(username);
		data.setPassword(pwd);
//		data.setDatetime(Calendar.getInstance());
		
		ArrayList<Card> cardList = getAllData();
		data.setCardList(cardList);
		String msg = SyncDataHelper.encode(data);
		String dataMsg= WebServiceHelper.post(urlname, "data="+msg);
		
		setAllData(SyncDataHelper.decode(dataMsg));
		return true;
	}
	
	/**
	 * 删除数据库中原有的所有数据
	 * @return 是否删除成功
	 * @throws SQLException
	 */
	private boolean deleteAllData() throws SQLException{
		ICardDataContext dao = MyApplication.cardDataContext;
		List<Card> cards = dao.queryForAll();
		Iterator<Card> it = cards.iterator();
		
		while(it.hasNext()){
			dao.delete(it.next().getId());
		}
		return true;
	}
	
	/**
	 * 把数据库的中数据设置为data中的数据 
	 * @param data 在设置 的数据
	 * @return 是否设置成功
	 * @throws SQLException
	 */
	private boolean setAllData(SyncData data) throws SQLException{
		deleteAllData();
		ICardDataContext dao = MyApplication.cardDataContext;
		List<Card> list = data.getCardList();
		Iterator<Card> it = list.iterator();
		
		while(it.hasNext()){
			Card card = it.next();
			dao.add(card);
		}
		
		return true;
	}
	
	/**
	 * 得到数据库中所有的数据
	 * @return 所有的数据
	 * @throws SQLException
	 */
	private  ArrayList<Card> getAllData() throws SQLException{
		ICardDataContext dao = MyApplication.cardDataContext;
		List<Card> list = dao.queryForAll();
		ArrayList<Card> cards = new ArrayList<Card>();
		Iterator<Card> it = list.iterator();
		while(it.hasNext()){
			cards.add(it.next());
		}
		return  cards;
	}
}
